package com.example.meterialproject.view.behavior.demo2

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.meterialproject.exts.name

/**
 *
 * @ClassName: HeadRecyclerViewBehavior
 * @Author: android 超级兵
 * @CreateDate: 4/14/22$ 10:32 AM$
 * TODO
 */
class HeadRecyclerViewBehavior(val context: Context, attrs: AttributeSet?) :
    CoordinatorLayout.Behavior<TextView>(context, attrs) {

    companion object {
        private const val TAG = "HeadRVBehavior"
    }
    /*
     * 作者:android 超级兵
     * 创建时间: 4/15/22 11:01 AM
     * TODO tips: 禁止 两个 Behavior 互相嵌套
     *  error: This graph contains cyclic dependencies
     * 错误原因: behavior 内部是通过 graph(图) 的数据结构 来存储,禁止循环依赖
     */
//    override fun layoutDependsOn(
//        parent: CoordinatorLayout,
//        child: TextView,
//        dependency: View
//    ): Boolean {
//        Log.i(TAG, "layoutDependsOn")
//        return dependency is RecyclerView
//    }

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: TextView,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        Log.i(TAG, "onStartNestedScroll target:${target.name}\ttarget:${target.name}")
        return target is RecyclerView
    }

    override fun onLayoutChild(
        parent: CoordinatorLayout,
        child: TextView,
        layoutDirection: Int
    ): Boolean {
        parent.onLayoutChild(child, layoutDirection)
        return super.onLayoutChild(parent, child, layoutDirection)
    }

    // 最后一次滑动距离
    private var lastScrollY = 0

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: TextView,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {

        // 最大滑动
        val maxScroll = -child.height

        // 最小滑动距离
        val minScroll = 0

        // 当前滑动距离 = 最后一次滑动距离 - 当前滑动距离
        var currentOffset = lastScrollY - dy

        // 当前消费的距离 Y

        currentOffset = when {
            currentOffset < maxScroll -> {
                maxScroll
            }
            currentOffset > minScroll -> {
                minScroll
            }
            else -> {
                currentOffset
            }
        }

        ViewCompat.offsetTopAndBottom(child, currentOffset - child.top)

        // 当前消费距离 - 最后一次消费距离 - 当前消费距离
        val consumedY: Int = lastScrollY - currentOffset

        // 记录当前滑动距离
        lastScrollY = currentOffset

        // 将当前记录的距离 传递给rv
        consumed[1] = consumedY
    }
}